package com.dhcc.bpm.common.interceptor;

import com.dhcc.bpm.modules.system.entity.User;
import com.dhcc.bpm.modules.system.service.IUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.api.ResultCode;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.jackson.JsonUtil;
import org.springblade.core.tool.utils.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;

/**
 * @ClassName SsoInterceptor
 * @Description 配置类
 * @Author lijiacheng
 * @Date 2020/2/21 0021 15:16
 * @Version V1.0
 * @Copyright: 2020 东华软件 . All rights reserved.
 **/

@Slf4j
@Component
@AllArgsConstructor
public class SsoInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    IUserService userService;

    @Autowired
    private Environment environment;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String ceairSso = environment.getProperty("bpm.ceair-sso");
        //SSO单点登录
        if(ceairSso.equals("true")){
            String ssoUserName = request.getHeader("USERNAME");
            String retireFlag = request.getHeader("retireFlag");
            log.info("ssoUserName----{}",ssoUserName);
            log.info("retireFlag----{}",retireFlag);
            if (ssoUserName == null){
                //没有登录，跳转到单点登录页面
                log.warn("SSO认证失败，请求接口：{}，请求IP：{}，请求参数：{}", request.getRequestURI(), WebUtil.getIP(request), JsonUtil.toJson(request.getParameterMap()));
                R result = R.fail(ResultCode.CEAIR_SSO_CANCEL);
                response.setCharacterEncoding(BladeConstant.UTF_8);
                response.setHeader(BladeConstant.CONTENT_TYPE_NAME, MediaType.APPLICATION_JSON_UTF8_VALUE);
                response.setStatus(HttpServletResponse.SC_OK);
                try {
                    response.getWriter().write(Objects.requireNonNull(JsonUtil.toJson(result)));
                } catch (IOException ex) {
                    log.error(ex.getMessage());
                }
                return false;
            } else {
                //先判断是否离退休人员
//                if("1".equals(retireFlag)){
//                    log.warn("SSO认证失败，请求接口：{}，请求IP：{}，请求参数：{}", request.getRequestURI(), WebUtil.getIP(request), JsonUtil.toJson(request.getParameterMap()));
//                    R result = R.fail(ResultCode.CEAIR_AUTH_CANCEL);
//                    response.setCharacterEncoding(BladeConstant.UTF_8);
//                    response.setHeader(BladeConstant.CONTENT_TYPE_NAME, MediaType.APPLICATION_JSON_UTF8_VALUE);
//                    response.setStatus(HttpServletResponse.SC_OK);
//                    try {
//                        response.getWriter().write(Objects.requireNonNull(JsonUtil.toJson(result)));
//                    } catch (IOException ex) {
//                        log.error(ex.getMessage());
//                    }
//                    return false;
//                }
                //判断该用户在不在系统里
                User user = userService.selectUserByaccount(ssoUserName);
                if(user == null){
                    //新建用户
                    User newUser = new User();
                    newUser.setAccount(ssoUserName);
                    newUser.setName(ssoUserName);
                    newUser.setCreateTime(new Date());
                    userService.submit(newUser);
                    log.warn("SSO认证失败，请求接口：{}，请求IP：{}，请求参数：{}", request.getRequestURI(), WebUtil.getIP(request), JsonUtil.toJson(request.getParameterMap()));
                    R result = R.fail(ResultCode.CEAIR_AUTH_CANCEL);
                    response.setCharacterEncoding(BladeConstant.UTF_8);
                    response.setHeader(BladeConstant.CONTENT_TYPE_NAME, MediaType.APPLICATION_JSON_UTF8_VALUE);
                    response.setStatus(HttpServletResponse.SC_OK);
                    try {
                        response.getWriter().write(Objects.requireNonNull(JsonUtil.toJson(result)));
                    } catch (IOException ex) {
                        log.error(ex.getMessage());
                    }
                    return false;
                }else {
                    //若用户没有权限
                    if(user.getRoleId() == null){
                        log.warn("SSO认证失败，请求接口：{}，请求IP：{}，请求参数：{}", request.getRequestURI(), WebUtil.getIP(request), JsonUtil.toJson(request.getParameterMap()));
                        R result = R.fail(ResultCode.CEAIR_AUTH_CANCEL);
                        response.setCharacterEncoding(BladeConstant.UTF_8);
                        response.setHeader(BladeConstant.CONTENT_TYPE_NAME, MediaType.APPLICATION_JSON_UTF8_VALUE);
                        response.setStatus(HttpServletResponse.SC_OK);
                        try {
                            response.getWriter().write(Objects.requireNonNull(JsonUtil.toJson(result)));
                        } catch (IOException ex) {
                            log.error(ex.getMessage());
                        }
                        return false;
                    }else {
                        return true;
                    }
                }
            }
        }else {
            return true;
        }
    }


}
